package com.zyx.concurrentdemo.mytest.c04;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/13 11:16
 */
@Slf4j(topic = "c.SafeCounterOopDemo")
public class SafeCounterOopDemo {

    public static void main(String[] args) throws InterruptedException {
        MyCounter counter = new MyCounter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increase();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.decrease();
            }
        }, "t2");

        t1.join();
        t2.join();

        log.debug("result =====>>>>> {}", counter.getCounter());
    }
}

class MyCounter {
    private int counter = 0;

    public void increase() {
        synchronized (this) {
            counter++;
        }
    }

    public void decrease() {
        synchronized (this) {
            counter--;
        }
    }

    public int getCounter() {
        synchronized (this) {
            return counter;
        }
    }

}